package producerandconsumer;

import lombok.SneakyThrows;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable{
    private volatile boolean isRunning = true;
    private BlockingQueue<PCData> queue;
    private static AtomicInteger count = new AtomicInteger();
    private int producerId;
    public Producer(BlockingQueue<PCData> queue,int producerId){
        this.queue = queue;
        this.producerId = producerId;
    }
    @SneakyThrows
    @Override
    public void run() {
        PCData data = null;
        Random r = new Random();
        System.out.println("start ProdutingId:"+producerId);
        try{
            while (isRunning){
                Thread.sleep(r.nextInt(1000));
                data = new PCData(count.incrementAndGet(),"第"+count+"号产品");
                System.out.println("生产者"+producerId+"--生产"+data.getName()+"并加入仓库中");
                if(!queue.offer(data,2, TimeUnit.SECONDS)){
                    System.err.println("加入队列失败！");
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void stop(){
        isRunning = false;
    }
}
